import React, {Component} from 'react';
import {Image, StyleSheet, Text, TouchableOpacity, View, AsyncStorage, ScrollView, Alert} from 'react-native';
import Toast from '@remobile/react-native-toast';
import {BasicStyle} from "../../../style/BasicStyle";
import {ShopCarStyle} from "../../../style/ShopStyle/ShopCarStyle";
import CountEmitter from './../../utils/event/CountEmitter';
import FetchUtils from './../../utils/FetchUtils';
import utils from './../../utils/utils';
import {ShopDetailStyle} from "../../../style/ShopStyle/ShopDetailStyle";

export default class ShopCar extends Component {

    static navigationOptions = ({navigation, screenProps}) => ({
        tabBarLabel: '购物车',
        tabBarIcon: ({tintColor, focused}) => (
            focused ?
                <Image style={{
                    height: utils.autoWidth(23),
                    width: utils.autoWidth(27)
                }} resizeMode='contain' source={require('./../../../img/cart_selected.png')}/>
                :
                <Image style={{
                    height: utils.autoWidth(23),
                    width: utils.autoWidth(27)
                }} resizeMode='contain' source={require('./../../../img/cart_unselected.png')}/>
        ),
        headerTitle: "购物车",
        headerTitleStyle: {
            alignSelf: 'center',
            fontSize: utils.setSpText(17),
        },
        headerStyle: {
            backgroundColor: '#F9F9F9',
        },
        headerRight: <TouchableOpacity/>,
        headerLeft: <TouchableOpacity/>,

    });

    constructor(props) {
        super(props);
        this.state = ({
            list: null
        });
        this._getShopCarData();
    }

    componentWillMount() {
        CountEmitter.addListener('ShopCarRefresh', () => {
            /*每次监听事件触发就更新购物车(因为我放在本地存储)*/
            this._getShopCarData();
        });
    }

    componentWillUnmount() {
        CountEmitter.removeListener('ShopCarRefresh', () => {
        });
    }

    render() {
        return (
            <View style={[BasicStyle.containerView, ShopCarStyle.containerView]}>
                {!this.state.list
                    ?
                    <Image style={{width: utils.autoWidth(101), height: utils.autoWidth(83)}} source={require('./../../../img/empty_cart_words.png')}/>
                    :
                    null
                }

                {!this.state.list
                    ?
                    <TouchableOpacity style={ShopCarStyle.emptyCarBut} onPress={this._emptyShopCarBut.bind(this)}>
                        <Text style={ShopCarStyle.emptyCarButText}>去商城看看</Text>
                    </TouchableOpacity>
                    :
                    null
                }

                {this.state.list
                    ?
                    <ScrollView
                        showsVerticalScrollIndicator={false}
                        showsHorizontalScrollIndicator={false}
                        removeClippedSubviews={false}
                    >
                        {this._shopCarListItem(this.state.list)}
                    </ScrollView>
                    :
                    null
                }

                {this.state.list
                    ?
                    <View style={{
                        height: utils.autoheight(60),
                        width: utils.screenWidth,
                        backgroundColor: '#FFF',
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        borderTopWidth: utils.autoheight(1),
                        borderColor: '#B2B2B2'
                    }}>
                        <View style={{marginLeft: utils.autoWidth(10)}}><Text
                            style={{fontSize: utils.setSpText(15), color: '#A0A0A0'}}>总计
                            （{this._getShopCarNum(this.state.list)} 件）：</Text></View>
                        <View style={{flexDirection: 'row', marginRight: utils.autoWidth(10)}}>
                            <Text style={{
                                fontSize: utils.setSpText(23),
                                color: '#D0021B',
                                marginRight: utils.autoWidth(10)
                            }}>¥ {this._getShopCarPrice(this.state.list)}</Text>
                            <TouchableOpacity style={{
                                height: utils.autoheight(40),
                                width: utils.autoWidth(120),
                                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                                borderRadius: utils.setSpText(3),
                                justifyContent: 'center',
                                alignItems: 'center'
                            }} onPress={() => {
                                this._confirmOrder();
                            }}>
                                <Text style={{fontSize: utils.setSpText(17), color: '#FFF'}}>去结算</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                    :
                    null
                }


            </View>
        );
    }

    /*购物车为空的按钮点击事件*/
    _emptyShopCarBut = () => {
        let {navigate} = this.props.navigation;
        navigate('ShopTab')
    };

    /*购物车列表*/
    _shopCarListItem = (list) => {
        let views = list.map((item, index) => {
            return <TouchableOpacity key={index}
                                     style={{
                                         height: utils.autoheight(125),
                                         width: utils.screenWidth,
                                         backgroundColor: '#FFF',
                                         marginBottom: utils.autoheight(1),
                                         flexDirection: 'row'
                                     }}
                                     onPress={() => {
                let {navigate} = this.props.navigation;
                navigate('ShopDetailNav',{productId: item.proId})
            }}
            >
                <Image source={{uri: utils.qiniuUrl + item.proMainImg + utils.qiniu200Url}} style={{
                    width: utils.autoWidth(70),
                    height: utils.autoheight(75),
                    marginLeft: utils.autoWidth(15),
                    marginTop: utils.autoheight(12)
                }}/>
                <View style={{marginLeft: utils.autoWidth(10), marginTop: utils.autoheight(12), flex: 1}}>
                    <Text style={{fontSize: utils.setSpText(17), color: '#000'}}>{item.proName}</Text>
                    <Text style={{
                        fontSize: utils.setSpText(15),
                        color: '#A0A0A0'
                    }}>“{item.proColor}”，“{item.proSize}”</Text>
                    <View style={{flexDirection: 'row'}}>
                        <Text style={{
                            fontSize: utils.setSpText(17),
                            color: '#000'
                        }}>{item.proNowPrice ? "¥ " + utils.toDecimal2(item.proNowPrice) + "  " : " "}</Text>
                        <Text style={{
                            fontSize: utils.setSpText(15),
                            color: '#A0A0A0',
                            textDecorationLine: 'line-through'
                        }}>{item.proOldPrice ? "¥ " + utils.toDecimal2(item.proOldPrice) + "  " : " "}</Text>
                    </View>
                    <View style={{flex: 1, flexDirection: 'row', justifyContent: 'space-between'}}>
                        <View style={ShopDetailStyle.shopCarModalNumView}>
                            <TouchableOpacity style={ShopDetailStyle.shopCarModalNumViewButRight}
                                              onPress={this._addOrRemoveNum.bind(this, list, item.proId, 'remove')}>
                                <Image style={ShopDetailStyle.shopCarModalNumViewButImg}
                                       source={require('./../../../img/remove.png')}
                                />
                            </TouchableOpacity>
                            <Text style={{
                                fontSize: utils.setSpText(21),
                                color: '#000'
                            }}>{item.proNum}</Text>
                            <TouchableOpacity style={ShopDetailStyle.shopCarModalNumViewButLeft}
                                              onPress={this._addOrRemoveNum.bind(this, list, item.proId, 'add')}>
                                <Image style={ShopDetailStyle.shopCarModalNumViewButImg}
                                       source={require('./../../../img/add.png')}/>
                            </TouchableOpacity>
                        </View>

                        <TouchableOpacity style={{marginRight: utils.autoWidth(16), marginTop: utils.autoheight(15)}}
                                          onPress={this._removeShopCarPrice.bind(this, list, item.proId, item.proColor, item.proSize)}
                        >
                            <Image style={ShopDetailStyle.shopCarModalNumViewButImg}
                                   source={require('./../../../img/gray_close.png')}/>
                        </TouchableOpacity>

                    </View>
                </View>
            </TouchableOpacity>
        });
        return views;
    };

    /*购物车上的按钮加减*/
    _addOrRemoveNum = (list, id, type) => {
        AsyncStorage.getItem("userId").then((userId) => {
            let newList = [];
            for (let n = 0; n < list.length; n++) {
                if (list[n].proId !== id) {
                    newList.push(list[n])
                } else {
                    if (type === 'add') {
                        let shopCarParam = {
                            proId: list[n].proId,
                            proMainImg: list[n].proMainImg,
                            proName: list[n].proName,
                            proColor: list[n].proColor,
                            proSize: list[n].proSize,
                            proNum: list[n].proNum + 1,
                            proNowPrice: list[n].proNowPrice,
                            proOldPrice: list[n].proOldPrice,
                        };
                        newList.push(shopCarParam);
                    } else if (type === 'remove') {
                        let shopCarParam = {
                            proId: list[n].proId,
                            proMainImg: list[n].proMainImg,
                            proName: list[n].proName,
                            proColor: list[n].proColor,
                            proSize: list[n].proSize,
                            proNum: list[n].proNum === 1 ? 1 : list[n].proNum - 1,
                            proNowPrice: list[n].proNowPrice,
                            proOldPrice: list[n].proOldPrice,
                        };
                        newList.push(shopCarParam);
                    }
                }
            }
            AsyncStorage.setItem("shopCar_" + userId, JSON.stringify(newList), (error) => {
                if (error) {
                    console.log(error);
                } else {
                    this._getShopCarData();
                }
            })
        });
    };

    /*获取购物车数据*/
    _getShopCarData = () => {
        AsyncStorage.getItem("userId").then((userId) => {
            AsyncStorage.getItem("shopCar_" + userId).then((shopCar) => {
                if (shopCar !== null) {
                    console.log(JSON.parse(shopCar));
                    this.setState({
                        list: JSON.parse(shopCar),
                    })
                }
            })

        })
    };
    /*计算购物车件数*/
    _getShopCarNum = (list) => {
        let sum = 0;
        for (let n = 0; n < list.length; n++) {
            sum = parseInt(list[n].proNum) + parseInt(sum);
        }
        return sum
    };
    /*计算购物车总价*/
    _getShopCarPrice = (list) => {
        let sum = 0;
        for (let n = 0; n < list.length; n++) {
            sum = parseFloat(list[n].proNowPrice) * parseInt(list[n].proNum) + parseFloat(sum);
        }
        return utils.toDecimal2(sum)
    };
    /*购物车删除*/
    _removeShopCarPrice = (list, id, color, size) => {
        Alert.alert("警告", "确认删除该购物车商品吗？", [
            {text: '取消'},
            {
                text: '确认', onPress: () => {
                AsyncStorage.getItem("userId").then((userId) => {
                    let newList = [];
                    for (let n = 0; n < list.length; n++) {
                        if (list[n].proId === id && list[n].proColor === color && list[n].proSize === size) {
                            console.log("你被删除咯！")
                        }else {
                            newList.push(list[n]);
                        }
                    }

                    AsyncStorage.setItem("shopCar_" + userId, newList.length > 0 ? JSON.stringify(newList) : JSON.stringify(null), (error) => {
                        if (error) {
                            console.log(error);
                        } else {
                            this._getShopCarData();
                        }
                    })
                })
            }
            }]);
    };

    /*确认订单*/
    _confirmOrder = () => {
        let {navigate} = this.props.navigation;
        navigate('ShopOrderNav');
    }

};